<%@ WebHandler Language="C#" Class="ImageHandler" %>

using System;
using System.Web;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Web.SessionState;
using System.Text;
using System.IO;
using SiteECSWeb;

public class ImageHandler : IHttpHandler, IReadOnlySessionState {

    public void ProcessRequest(HttpContext context)
    {
        FileInfo imageInfo = null;

        string imagePath = context.Request.QueryString["image"];
        
        if (imagePath == null )
        {
            return;
        }

        if (string.IsNullOrEmpty(imagePath))
        {
            imagePath = Globals.Settings.UploadInfo.ImgEmptyPathSmall;
        }
        else
        {
            if (imagePath.ToUpper().Contains(".PDF"))
            {
                imagePath = @"Images\\OfficeIcons\\pdf_bg.gif";
                imageInfo = new FileInfo(context.Server.MapPath(imagePath.Replace(@"\", @"\\")));
            }
            else if (imagePath.ToUpper().Contains(".DOC"))
            {
                imagePath = @"Images\\OfficeIcons\\word_bg.gif";
                imageInfo = new FileInfo(context.Server.MapPath(imagePath.Replace(@"\", @"\\")));
            }
            else if (imagePath.ToUpper().Contains(".XLS"))
            {
                imagePath = @"Images\\OfficeIcons\\excel_bg.gif";
                imageInfo = new FileInfo(context.Server.MapPath(imagePath.Replace(@"\", @"\\")));
            }
            else
            {
                imageInfo = new FileInfo(context.Server.MapPath
                    (Globals.Settings.UploadInfo.RootAttachFolder + imagePath.Replace(@"\", @"\\")));
            }
        }

        

        bool hotlinked = true; long key;

        if (long.TryParse(context.Request.QueryString["key"], out key))
        {
            hotlinked = !HotlinkProtection.IsKeyValid(key, 30);
        }
        else
        {
            hotlinked = true;
        }
        
        PhotoSize size = ImageHelper.GetSizeParam(context);


        Image cachedImage = context.Cache[GetCacheKey(imageInfo.FullName, hotlinked)] as Image;

        if (cachedImage != null)
        {
            Size newSize = ImageHelper.CalculateDimensions(cachedImage.Size, (int)size);

            using (Bitmap bitmapCopy = new Bitmap(cachedImage, newSize))
            {
                using (MemoryStream mStream = new MemoryStream())
                {
                    context.Response.ContentType = ImageHelper.GetContentType(imageInfo);
                    bitmapCopy.Save(mStream, ImageHelper.GetImageFormat(imageInfo));
                    mStream.WriteTo(context.Response.OutputStream);
                }                
            }
            return;
        }


        
        using (Image img = ConvertFromIndexed(Image.FromFile(imageInfo.FullName)))
        {
            Size newSize = ImageHelper.CalculateDimensions(img.Size, (int)size);

            string watermark = "Copyright " +
                        ImageHelper.GetCopyrightYear(img, DateTime.Now.Year.ToString());
            string sitename = "www.ecs.gov.eg";

            using (Bitmap bitmapCopy = new Bitmap(img, newSize))
            {
                using (Graphics graphics = Graphics.FromImage(bitmapCopy))
                {
                    int fontsize = 10;
                    if (bitmapCopy.Width > 400) fontsize = 12;
                    if (bitmapCopy.Width <= 100) fontsize = 6;


                    Font font = new Font("Verdana", fontsize, FontStyle.Bold,
                        GraphicsUnit.Pixel);
                    graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
                    if (hotlinked)
                    {
                        ImageHelper.WriteHotlinkMessage(context, bitmapCopy, sitename, graphics, font);
                    }
                    ImageHelper.WriteWatermark(bitmapCopy, watermark, graphics, font);

                    context.Cache.Insert(GetCacheKey(imagePath, hotlinked), bitmapCopy.Clone());


                    graphics.SmoothingMode = SmoothingMode.HighQuality;
                    graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                    graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
                    graphics.DrawImage(bitmapCopy, new Rectangle(new Point(0, 0), newSize));
                    context.Response.ContentType = ImageHelper.GetContentType(imageInfo);
                    using (MemoryStream mStream = new MemoryStream())
                    {
                        bitmapCopy.Save(mStream, ImageHelper.GetImageFormat(imageInfo));
                        mStream.WriteTo(context.Response.OutputStream);
                    }
                }
            }
            context.Response.End();
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
    private string GetCacheKey(string imagePath, bool hotlinked)
    {
        string cacheKey = imagePath;
        if (hotlinked) cacheKey += "_linked";
        return cacheKey;
    }



    private Image ConvertFromIndexed(Image image)
    {
        switch (image.PixelFormat)
        {
            case PixelFormat.Format1bppIndexed:
            case PixelFormat.Format4bppIndexed:
            //case PixelFormat.Format8bppIndexed:
            case PixelFormat.Format16bppArgb1555:
            case PixelFormat.Format16bppGrayScale:

                //The image is in an indexed pixel format
                //Convert by copying to a new image.
                using (Bitmap newImage = new Bitmap(image.Width, image.Height,
                    PixelFormat.Format32bppArgb))
                {
                    newImage.SetResolution(
                    image.HorizontalResolution,
                    image.VerticalResolution);
                    using (Graphics g = Graphics.FromImage(newImage))
                    {
                        g.DrawImageUnscaled(image, 0, 0);
                        g.Dispose();
                    } 
                    return newImage;
                }
            
                //using (Bitmap newImage = new Bitmap(image.Width, image.Height,
                //    PixelFormat.Format16bppArgb1555 ))
                //{
                //    newImage.SetResolution(
                //    image.HorizontalResolution,
                //    image.VerticalResolution);
                //    using (Graphics g = Graphics.FromImage(newImage))
                //    {
                //        g.DrawImageUnscaled(image, 0, 0);
                //        g.Dispose();
                //    }
                //    return newImage;
                //}
            default:
                return image;
        }
    }
}